package rest.jbpm.filters;

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

public class ClearNamespaceFilter implements ContainerResponseFilter {

    private static Logger log = LoggerFactory.getLogger(ClearNamespaceFilter.class);
    private static TransformerFactory factory = TransformerFactory.newInstance();
    public static final String CLEANUP = "cleanup";

	@Override
	public ContainerResponse filter(ContainerRequest request,
			ContainerResponse response) {
		
		if(request.getQueryParameters().containsKey(CLEANUP)
				&& (response.getEntity() instanceof String)) {
			
			log.debug("removing namespaces & prifixes from xml");
			StringWriter sw = new StringWriter();
			StringWriter out = new StringWriter();
			try {

				Transformer transformer = factory.newTransformer(new StreamSource(
								JaxbFilter.class.getClassLoader()
								.getResourceAsStream("xslt/clear-namespace.xsl")));
				transformer.transform(
						new StreamSource(new StringReader((String) response.getEntity())), 
						new StreamResult(out));
				
			} catch (TransformerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.setEntity(out.toString());
			return response;
		}
		
		log.debug("no cleanup required");
		return response;
	}
	
}
